<?php

namespace End01here\EasySms;


use End01here\EasySms\Contracts\PhoneNumberInterface;
use End01here\EasySms\Exceptions\PhoneErrorException;

/**
 * 手机号码对象
 * Class EasySmsService
 * @package End01here\EasySms
 */
class PhoneNumberServer implements PhoneNumberInterface
{

    /**
     * @var int
     */
    protected $number;

    /**
     * @var int
     */
    protected $IDDCode;

    /**
     * 初始化对象，并且验证手机号码格式
     * @param int $numberWithoutIDDCode
     * @param string $IDDCode
     */
    public function __construct($numberWithoutIDDCode, $IDDCode = '86')
    {
        $this->number = $numberWithoutIDDCode;
        $this->verifyPhoneNumber();
        $this->IDDCode = $IDDCode ? intval(ltrim($IDDCode, '+0')) : null;
    }


    /**
     * 验证手机号码格式
     * @throws PhoneErrorException
     */
    private function verifyPhoneNumber()
    {
        if (!preg_match('#^[\d]{11,11}$#', $this->number)) {
            throw  new PhoneErrorException('手机号码格式错误', 0);
        }
    }

    /**
     * 获取前缀
     * @return int
     */
    public function getIDDCode()
    {
        return $this->IDDCode;
    }

    /**
     * 获取纯手机号码
     * @return int
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * 获取+  格式
     * @return string
     */
    public function getUniversalNumber()
    {
        return $this->getPrefixedIDDCode('+') . $this->number;
    }

    /**
     * 获取00 格式
     *
     * @return string
     */
    public function getZeroPrefixedNumber()
    {
        return $this->getPrefixedIDDCode('00') . $this->number;
    }

    /**
     * @param string $prefix
     *
     * @return string|null
     */
    public function getPrefixedIDDCode($prefix)
    {
        return $this->IDDCode ? $prefix . $this->IDDCode : null;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->getUniversalNumber();
    }

    /**
     * Specify data which should be serialized to JSON.
     *
     * @see  http://php.net/manual/en/jsonserializable.jsonserialize.php
     *
     * @return mixed data which can be serialized by <b>json_encode</b>,
     *               which is a value of any type other than a resource
     *
     * @since 5.4.0
     */
    public function jsonSerialize()
    {
        return $this->getUniversalNumber();
    }

}
